<?php if (!defined('CORE_DIR')) die('Wrong entry point!');

/* 
 * Copyright 2010 Anton Muraviev a.k.a kuromaisu
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */


Aero::define('DateFormControl', AS_CLASS);
Aero::import('libs/form_controls/group');

// Set default timezone
date_default_timezone_set(Aero::option('time.timezone','UCT'));

/* -----------------------------------------------------------------------------
 * Class: DateFormControl
 * -----------------------------------------------------------------------------
 *
 */
class DateFormControl extends GroupFormControl
{
	protected function _initialize()
	{
		$this->template = '{day} / {month} / {year}';
		$this->controls = array(
			'day' => array(
				'control' => 'text',
				'control_class' => 'date-day'
			),
			'month' => array(
				'control' => 'text',
				'control_class' => 'date-month'
			),
			'year' => array(
				'control' => 'text',
				'control_class' => 'date-year'
			),
		);
		
		$this->constraints->addContext($this->constraints);
		$this->constraints->addContext($this);
		
		if (!$this->constraints->has('valid_date'))
		{
			$this->constraints->prepend('valid_date');
		}
		
		parent::_initialize();
	}
	
	protected function _serialize($values)
	{
		if (empty($values['year']) && empty($values['month']) && empty($values['day']))
		{
			return null;
		}
		
		return $values['year'] . '-' . $values['month'] . '-' . $values['day'];
	}
	
	protected function _unserialize($string)
	{
		if (1 === preg_match('~^(\d*)-(\d*)-(\d*)~',$string,$date))
		{
			return array(
				'day' => $date[3],
				'month' => $date[2],
				'year' => $date[1]
			);
		}
		
		return array(
			'day' => '',
			'month' => '',
			'year' => ''
		);
	}
	
	public function validate()
	{
		return BaseFormControl::validate();
	}
	
	public function constrain($value, $constraint, $arguments)
	{
		switch ($constraint)
		{
			case 'valid_date':
				if (is_null($value))
				{
					return true;
				}
				
				$result = strtotime($value);
				
				return $result !== FALSE && $result !== -1;
		}
		
		return null;
	}
}